#include <iostream>
#include <fstream>
#include <vector>
#include <filesystem>
#include <random>
#include "tire.h"
#include "chassis.h"
#include "agx_kit.h"
#include "camera.h"
#include "lidar.h"
#include "gyroscope.h"
#include "lcd.h"
#include "battery.h"
#include "student.h"

class Car {
public:
    std::string id;
    Chassis chassis;
    AGXKit agxKit;
    Camera camera;
    Lidar lidar;
    Gyroscope gyroscope;
    LCD lcd;
    Battery battery;
    Student assignedStudent;

    void setID(const std::string& newId) {
        id = newId;
    }

    void print() const {
        std::cout << "===== 车辆配置信息 =====" << std::endl;
        std::cout << "车辆编号: " << id << std::endl;
        chassis.print();
        agxKit.print();
        camera.print();
        lidar.print();
        gyroscope.print();
        lcd.print();
        battery.print();
        std::cout << "分配学生: ";
        assignedStudent.print();
    }

    void save(std::ofstream& out) const {
        out << "===== 车辆配置信息 =====" << std::endl;
        out << "车辆编号: " << id << std::endl;
        chassis.save(out);
        agxKit.save(out);
        camera.save(out);
        lidar.save(out);
        gyroscope.save(out);
        lcd.save(out);
        battery.save(out);
        out << "分配学生: ";
        assignedStudent.save(out);
    }
};

bool validateCarID(const std::string& id) {
    if (id.length() != 16) return false;
    if (id.substr(0, 5) != "cqusn") return false;
    for (char c : id.substr(5)) {
        if (!isalnum(c)) return false;
    }
    return true;
}

bool validateChassisID(const std::string& id) {
    if (id.length() != 8) return false;
    if (id.substr(0, 2) != "dp") return false;
    for (char c : id.substr(2)) {
        if (!isalnum(c)) return false;
    }
    return true;
}

void initCar(Car& car, int index, bool debug = false) {
    if (debug) {
        // 调试模式自动生成编号
        car.setID("cqusn" + std::to_string(100000000 + index).substr(1));
        car.chassis.setId("dp" + std::to_string(100000 + index).substr(1));
    } else {
        // 非调试模式手动输入编号
        std::string carId, chassisId;
        
        do {
            std::cout << "请输入小车编号(cqusn打头的16位数字+字母): ";
            std::cin >> carId;
            if (!validateCarID(carId)) {
                std::cout << "编号格式错误，请重新输入" << std::endl;
            }
        } while (!validateCarID(carId));
        
        do {
            std::cout << "请输入底盘编号(dp打头的8位数字+字母): ";
            std::cin >> chassisId;
            if (!validateChassisID(chassisId)) {
                std::cout << "编号格式错误，请重新输入" << std::endl;
            }
        } while (!validateChassisID(chassisId));
        
        car.setID(carId);
        car.chassis.setId(chassisId);
    }

    // 设置轮胎属性
    Tire tire;
    tire.setType(debug ? "测试轮胎" + std::to_string(index) : "高性能轮胎" + std::to_string(index));
    tire.setSize("235/55 R18");

    // 设置底盘其他属性
    car.chassis.setModel("标准底盘");
    car.chassis.setWheelbase("2800mm");
    car.chassis.setTrack("1600mm");
    car.chassis.setMinClearance("180mm");
    car.chassis.setMinTurnRadius("5.5m");
    car.chassis.setDriveType("四驱");
    car.chassis.setMaxRange("500km");
    car.chassis.addTire(tire);

    // 设置其他模块属性...
}

void loadFromFile(std::vector<Car>& cars, const std::string& filename) {
    if (std::filesystem::exists(filename)) {
        std::ifstream in(filename);
        if (in.is_open()) {
            std::cout << "从文件加载配置..." << std::endl;
            std::string line;
            int carIndex = 0;
            while (std::getline(in, line) && carIndex < 10) {
                if (line.find("车辆编号:") != std::string::npos) {
                    cars[carIndex].setID(line.substr(line.find(":") + 2));
                    // 继续读取其他模块信息...
                    carIndex++;
                }
            }
            in.close();
        }
    }
}

void modifyCarModules(Car& car) {
    while (true) {
        std::cout << "\n修改车辆模块信息:" << std::endl;
        std::cout << "0. 修改小车编号" << std::endl;
        std::cout << "1. 修改底盘信息" << std::endl;
        std::cout << "2. 修改AGX套件信息" << std::endl;
        std::cout << "3. 修改摄像头信息" << std::endl;
        std::cout << "4. 修改激光雷达信息" << std::endl;
        std::cout << "5. 修改陀螺仪信息" << std::endl;
        std::cout << "6. 修改液晶屏信息" << std::endl;
        std::cout << "7. 修改电池信息" << std::endl;
        std::cout << "q. 返回上级菜单" << std::endl;
        std::cout << "请选择操作: ";

        char cmd;
        std::cin >> cmd;

        switch (cmd) {
            case '0': {
                std::string carId;
                do {
                    std::cout << "请输入小车编号(cqusn打头的16位数字+字母): ";
                    std::cin >> carId;
                    if (!validateCarID(carId)) {
                        std::cout << "编号格式错误，请重新输入" << std::endl;
                    }
                } while (!validateCarID(carId));
                car.setID(carId);
                break;
            }
            case '1': {
                std::string id, model, wheelbase, track, clearance, radius, drive, range;
                std::cout << "输入底盘ID: ";
                std::cin >> id;
                std::cout << "输入型号: ";
                std::cin >> model;
                std::cout << "输入轴距: ";
                std::cin >> wheelbase;
                std::cout << "输入轮距: ";
                std::cin >> track;
                std::cout << "输入最小离地间隙: ";
                std::cin >> clearance;
                std::cout << "输入最小转弯半径: ";
                std::cin >> radius;
                std::cout << "输入驱动类型: ";
                std::cin >> drive;
                std::cout << "输入最大续航: ";
                std::cin >> range;
                
                car.chassis.setId(id);
                car.chassis.setModel(model);
                car.chassis.setWheelbase(wheelbase);
                car.chassis.setTrack(track);
                car.chassis.setMinClearance(clearance);
                car.chassis.setMinTurnRadius(radius);
                car.chassis.setDriveType(drive);
                car.chassis.setMaxRange(range);
                break;
            }
            case '2': {
                std::string model, ai, vram, storage;
                int cuda_cores, tensor_cores;
                std::cout << "输入AGX套件型号: ";
                std::cin >> model;
                std::cout << "输入AI算力: ";
                std::cin >> ai;
                std::cout << "输入CUDA核心数: ";
                std::cin >> cuda_cores;
                std::cout << "输入Tensor核心数: ";
                std::cin >> tensor_cores;
                std::cout << "输入显存: ";
                std::cin >> vram;
                std::cout << "输入存储: ";
                std::cin >> storage;
                
                car.agxKit.setModel(model);
                car.agxKit.setAI(ai);
                car.agxKit.setCudaCores(cuda_cores);
                car.agxKit.setTensorCores(tensor_cores);
                car.agxKit.setVRAM(vram);
                car.agxKit.setStorage(storage);
                break;
            }
            // 其他模块修改逻辑类似...
            case 'q':
                return;
            default:
                std::cout << "无效输入" << std::endl;
        }
    }
}

void assignCars(std::vector<Car>& cars) {
    int current = 0;
    while (true) {
        std::cout << "\n当前车辆 (" << current+1 << "/10):" << std::endl;
        cars[current].print();
        
        std::cout << "\n操作选项:" << std::endl;
        std::cout << "1. 修改学生信息" << std::endl;
        std::cout << "2. 修改车辆信息" << std::endl;
        std::cout << "n. 下一辆车" << std::endl;
        std::cout << "p. 上一辆车" << std::endl;
        std::cout << "q. 退出分配" << std::endl;
        std::cout << "请选择操作: ";

        char cmd;
        std::cin >> cmd;

        switch (cmd) {
            case '1': {
                Student student;
                std::cout << "请输入学号: ";
                std::cin >> student.id;
                std::cout << "请输入姓名: ";
                std::cin >> student.name;
                cars[current].assignedStudent = student;
                break;
            }
            case '2':
                modifyCarModules(cars[current]);
                break;
            case 'n':
                if (current < 9) current++;
                else std::cout << "已经是最后一辆车" << std::endl;
                break;
            case 'p':
                if (current > 0) current--;
                else std::cout << "已经是第一辆车" << std::endl;
                break;
            case 'q':
                return;
            default:
                std::cout << "无效输入" << std::endl;
        }

        // 保存修改
        std::ofstream out("car_config.txt");
        if (out.is_open()) {
            for (const auto& car : cars) {
                car.save(out);
                out << "\n";
            }
            out.close();
        }
    }
}

int main(int argc, char* argv[]) {
    bool debug = false;
    for (int i = 1; i < argc; ++i) {
        std::string arg = argv[i];
        if (arg == "--debug" || arg == "-d") {
            debug = true;
        }
    }

    std::vector<Car> cars(10);
    
    if (std::filesystem::exists("car_config.txt")) {
        loadFromFile(cars, "car_config.txt");
        if (debug) {
            // 调试模式重新初始化
            for (int i = 0; i < cars.size(); i++) {
                initCar(cars[i], i + 1, true);
            }
        }
    } else {
        // 初始化10辆车
        for (int i = 0; i < cars.size(); i++) {
            initCar(cars[i], i + 1, debug);
        }
    }

    assignCars(cars);

    // 保存信息到文件
    std::ofstream out("car_config.txt");
    if (out.is_open()) {
        for (const auto& car : cars) {
            car.save(out);
            out << "\n";
        }
        out.close();
        std::cout << "配置已保存到 car_config.txt" << std::endl;
    }

    return 0;
}